const adminService = require('../services/adminService');

/**
 * 权限检查中间件
 * @param {string} resource - 资源名称
 * @param {string} action - 操作类型
 */
const checkPermission = (resource, action) => {
  return async (req, res, next) => {
    try {
      // 确保已通过管理员认证
      if (!req.admin || !req.adminId) {
        return res.status(401).json({
          success: false,
          message: '请先进行管理员认证'
        });
      }

      // 检查权限
      const hasPermission = await adminService.checkPermission(req.adminId, resource, action);
      
      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: `权限不足，需要 ${resource}:${action} 权限`
        });
      }

      next();
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '权限检查失败',
        error: error.message
      });
    }
  };
};

/**
 * 检查多个权限（满足其中一个即可）
 * @param {Array} permissions - 权限数组 [{resource, action}, ...]
 */
const checkAnyPermission = (permissions) => {
  return async (req, res, next) => {
    try {
      if (!req.admin || !req.adminId) {
        return res.status(401).json({
          success: false,
          message: '请先进行管理员认证'
        });
      }

      let hasPermission = false;
      
      for (const permission of permissions) {
        const result = await adminService.checkPermission(
          req.adminId, 
          permission.resource, 
          permission.action
        );
        
        if (result) {
          hasPermission = true;
          break;
        }
      }

      if (!hasPermission) {
        const permissionStrings = permissions.map(p => `${p.resource}:${p.action}`);
        return res.status(403).json({
          success: false,
          message: `权限不足，需要以下权限之一：${permissionStrings.join(', ')}`
        });
      }

      next();
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '权限检查失败',
        error: error.message
      });
    }
  };
};

/**
 * 检查多个权限（必须全部满足）
 * @param {Array} permissions - 权限数组 [{resource, action}, ...]
 */
const checkAllPermissions = (permissions) => {
  return async (req, res, next) => {
    try {
      if (!req.admin || !req.adminId) {
        return res.status(401).json({
          success: false,
          message: '请先进行管理员认证'
        });
      }

      for (const permission of permissions) {
        const hasPermission = await adminService.checkPermission(
          req.adminId, 
          permission.resource, 
          permission.action
        );
        
        if (!hasPermission) {
          return res.status(403).json({
            success: false,
            message: `权限不足，需要 ${permission.resource}:${permission.action} 权限`
          });
        }
      }

      next();
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '权限检查失败',
        error: error.message
      });
    }
  };
};

module.exports = {
  checkPermission,
  checkAnyPermission,
  checkAllPermissions
};